package com.example.filesplit.demos.service;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DepartmentService {

    public List<String> getDepartmentList(String departmentFileName, String splitPath, String templateFile, List<String[]> alldata1, String logText) throws IOException {
        List<String> cNames = new ArrayList<>();

        // 读取部门名称
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(departmentFileName), "UTF-8"))) {
            String line;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                cNames.add(line);
                System.out.println("\t 任务分解：" + line);
                insertLog("\t 任务分解：" + line, logText);

                List<String[]> unitName = new ArrayList<>();
                for (String[] row : alldata1) {
                    if (row[3].contains(line)) {
                        unitName.add(row);
                    }
                }

                // 处理模板文档
                if (!unitName.isEmpty()) {
                    try (XWPFDocument templateDoc = new XWPFDocument(new FileInputStream(templateFile))) {
                        XWPFTable table = templateDoc.getTableArray(0);
                        for (String[] unit : unitName) {
                            XWPFTableRow newRow = table.createRow();
                            for (int i = 0; i < unit.length; i++) {
                                newRow.getCell(i).setText(unit[i]);
                            }
                        }
                        templateDoc.write(new FileOutputStream(splitPath + "\\" + "(" + line + ").docx"));
                    }
                }
            }
        }
        return cNames;
    }

    public void mergeFile(String similarFileName, String prePath, String logText) throws IOException {
        System.out.println("开始对同义单位进行合并……");
        insertLog("开始对同义单位进行合并……", logText);

        // 使用不同的变量名来避免冲突
        List<String[]> similarUnitTable = Files.readAllLines(Paths.get(similarFileName)).stream()
                .map(line -> line.split(" "))
                .collect(Collectors.toList());

        for (String[] units : similarUnitTable) {
            String sendUnitName = prePath + "\\" + "(" + units[0] + ").docx";
            for (int j = 1; j < units.length; j++) {
                String sameUnitName = prePath + "\\" + "(" + units[j] + ").docx";
                if (Files.exists(Paths.get(sameUnitName))) {
                    System.out.println("\t开始合并：" + sendUnitName + " " + sameUnitName);
                    insertLog("\t开始合并：" + sendUnitName + sameUnitName, logText);

                    try (XWPFDocument sendUnitDoc = new XWPFDocument(new FileInputStream(sendUnitName));
                         XWPFDocument sameUnitDoc = new XWPFDocument(new FileInputStream(sameUnitName))) {

                        XWPFTable sendUnitTable = sendUnitDoc.getTableArray(0);
                        XWPFTable sameUnitTableDoc = sameUnitDoc.getTableArray(0); // 重命名为 sameUnitTableDoc

                        for (int i = 1; i < sameUnitTableDoc.getRows().size(); i++) {
                            XWPFTableRow newRow = sendUnitTable.createRow();
                            for (int k = 0; k < sameUnitTableDoc.getRow(i).getTableCells().size(); k++) {
                                newRow.getCell(k).setText(sameUnitTableDoc.getRow(i).getCell(k).getText());
                            }
                        }
                        sendUnitDoc.write(new FileOutputStream(sendUnitName));
                    }
                } else {
                    Files.copy(Paths.get(sameUnitName), Paths.get(sendUnitName));
                }
            }
        }
    }

    private void insertLog(String message, String logText) {
        // 实现日志记录逻辑
        System.out.println(message);
    }
}